<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--代理商数据-->
      <el-col :span="4" :xs="24" v-if="rolesKey == '00'">
        <div class="head-container">
          <el-input
            v-model="merchantName"
            placeholder="请输入代理商名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="deptOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="merchantTree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="rolesKey == '00' ? 20 : 24" :xs="24">
        <el-form
          :model="queryParams"
          ref="queryForm"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="商户名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入商户名称"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商户手机号码" label-width="100px" prop="phone">
            <el-input
              v-model="queryParams.phone"
              placeholder="请输入商户手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="商户状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="商户状态"
              clearable
              size="small"
              style="width: 240px"
            >
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
              >重置</el-button
            >
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['system:shop:manager:add']"
              >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              :loading="exportLoading"
              @click="handleExport"
              v-hasPermi="['system:shop:manager:export']"
              >导出
            </el-button>
          </el-col>
          <right-toolbar
            :showSearch.sync="showSearch"
            @queryTable="getList"
            :columns="columns"
          ></right-toolbar>
        </el-row>

        <el-table
          v-loading="loading"
          :data="userList"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column
            label="商家头像"
            width="110px"
            align="center"
            key="pic"
          >
            <template slot-scope="scope">
              <el-image
                :src="scope.row.pic"
                style="width: 100px; height: 100px"
                fit="cover"
              ></el-image>
            </template>
          </el-table-column>
          <!-- <el-table-column label="商家ID" align="center" key="id" prop="id"  :show-overflow-tooltip="true" /> -->
          <el-table-column
            label="商户名称"
            align="center"
            key="name"
            prop="name"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="负责人"
            align="center"
            key="leader	"
            prop="leader"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="代理商名称	"
            align="center"
            key="proxyName"
            prop="proxyName"
            width="120"
          />
          <el-table-column
            label="商户手机号码	"
            align="center"
            key="phone"
            prop="phone"
            width="120"
          />
          <!-- <el-table-column label="营业时间" align="center" key="businessTime" prop="businessTime" :show-overflow-tooltip="true" /> -->
          <!-- <el-table-column label="商户邮箱" align="center" key="email" prop="email" :show-overflow-tooltip="true" /> -->
          <el-table-column
            label="热度"
            align="center"
            key="heat"
            prop="heat"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="商户余额	"
            align="center"
            key="videoCount"
            prop="videoCount"
            width="120"
          />
          <el-table-column label="商户状态" align="center" key="status">
            <template slot-scope="scope">
              <span style="color: #3894ff" v-if="scope.row.status == 0"
                >正常</span
              >
              <span style="color: #ed5565" v-if="scope.row.status == 1"
                >停用</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="是否是代理商"
            key="isProxy"
            width="100"
            align="center"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.isProxy == 0">否</span>
              <span v-if="scope.row.isProxy == 1">是</span>
            </template>
          </el-table-column>

          <el-table-column
            label="操作"
            align="center"
            width="250px"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['system:shop:manager:edit']"
                >修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-check"
                @click="TiktokEmpower(scope.row)"
                >抖音授权
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="getTikTokInfo(scope.row)"
                >修改抖音信息
              </el-button>
              <el-button
                v-if="rolesKey == '00'"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleRecharge(scope.row, 1)"
                >充值
              </el-button>
              <el-button
                v-if="rolesKey == '01'"
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleRecharge(scope.row, 2)"
                >充值
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUserList(scope.row)"
                >查看用户
              </el-button>
              <el-button size="mini" type="text" @click="getDetail(scope.row)"
                >查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>
    <!--    抖音授权二维码-->
    <el-dialog
      title="请打开抖音扫码"
      :visible.sync="codeOpen"
      width="300px"
      append-to-body
    >
      <div
        id="qrCode"
        style="display: flex; justify-content: center"
        ref="qrCodeDiv"
      ></div>
    </el-dialog>
    <!-- 商家抖音信息-->
    <el-dialog
      title="商家抖音信息"
      :visible.sync="TikTokOpen"
      width="1000px"
      append-to-body
    >
      <el-form
        ref="TikTokForm"
        :model="TikTokForm"
        :rules="rules"
        label-width="120px"
      >
        <el-row>
          <el-col :span="24">
            <el-col :span="12">
              <el-form-item label="用户名称" prop="nickname">
                <el-input
                  v-model="TikTokForm.nickname"
                  placeholder="请输入商户名称"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="商家抖音主页	" prop="douyinUrl">
                <el-input
                  v-model="TikTokForm.douyinUrl"
                  placeholder="商家抖音主页"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="是否显示小程序">
                <el-switch
                  v-model="miniSwitch"
                  active-text="是"
                  inactive-text="否"
                >
                </el-switch>
              </el-form-item>
            </el-col>
            <template v-if="miniSwitch">
              <el-col :span="12">
                <el-form-item label="抖音小程序标题" prop="miniAppTitle">
                  <el-input
                    v-model="TikTokForm.miniAppTitle"
                    placeholder="抖音小程序标题"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="抖音小程序地址" prop="miniAppUrl">
                  <el-input
                    v-model="TikTokForm.miniAppUrl"
                    placeholder="抖音小程序地址"
                    maxlength="50"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="抖音小程序id	" prop="miniAppId">
                  <el-input
                    v-model="TikTokForm.miniAppId"
                    placeholder="请输入抖音小程序id	"
                  />
                </el-form-item>
              </el-col>
            </template>

            <el-col :span="12">
              <el-form-item label="地址位置名称">
                <el-select
                  v-model="TikTokForm.address"
                  filterable
                  remote
                  reserve-keyword
                  width="180"
                  placeholder="请输入地址位置名称"
                  @change="changePoi"
                  :remote-method="remoteMethod"
                  :loading="loading"
                >
                  <el-option
                    v-for="item in poiList"
                    :key="item.id"
                    :value="item.address"
                    :label="item.address"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址" prop="address">
                <el-input
                  v-model="TikTokForm.address"
                  placeholder="请输入地址"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地理位置id	" prop="poiId">
                <el-input
                  v-model="TikTokForm.poiId"
                  placeholder="地理位置id	"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址经度	" prop="log">
                <el-input
                  v-model="TikTokForm.log"
                  :disabled="true"
                  placeholder="地址经度	"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址纬度	" prop="log">
                <el-input
                  v-model="TikTokForm.lat"
                  :disabled="true"
                  placeholder="地址纬度	"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="updateTiktokInfo">确 定</el-button>
        <el-button @click="TikTokCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--查看商户下用户列表弹窗-->
    <el-dialog
      title="用户列表"
      :visible.sync="userOpen"
      width="1000px"
      append-to-body
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="6">
          <el-button type="primary" plain @click="handleUserAdd"
            >新增</el-button
          >
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="merchantUserList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          label="账号"
          align="center"
          key="userName"
          prop="userName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="用户昵称"
          align="center"
          key="nickName"
          prop="nickName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="商户名称"
          align="center"
          key="shopName"
          prop="shopName"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="创建时间"
          align="center"
          key="createTime"
          prop="createTime"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="用户状态" align="center" key="status">
          <template slot-scope="scope">
            <span style="color: #3894ff" v-if="scope.row.status == 0"
              >正常</span
            >
            <span style="color: #ed5565" v-if="scope.row.status == 1"
              >停用</span
            >
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUserUpdate(scope.row)"
              v-hasPermi="['system:shop:user:edit']"
              >修改
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-refresh-right"
              @click="handleResetPwd(scope.row)"
              v-hasPermi="['system:shop:user:resetPwd']"
            >重置密码
            </el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="delShopUser(scope.row)"
              v-hasPermi="['system:shop:manager:deleteUser']"
              >删除
            </el-button>
            <el-button
              size="min"
              type="text"
              icon="el-icon-s-grid"
              @click="managerPush(scope.row)"
              >推广列表
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="userTotal > 0"
        :total="userTotal"
        :page.sync="userForm.pageNum"
        :limit.sync="userForm.pageSize"
        @pagination="getList"
      />
    </el-dialog>


    <el-dialog
      title="推广列表"
      :visible.sync="pushOpen"
      width="1000px"
      append-to-body
    >
      <el-descriptions :column="2" :colon="false">
        <el-descriptions-item>总推广人数 :&emsp;<span style="font-size: 15px; color:#1890ff">{{pushCountForm.totalCount}}</span></el-descriptions-item>
        <el-descriptions-item>成功核销人数 :&emsp;<span style="font-size: 15px; color:#1890ff">{{pushCountForm.checkCount}}</span></el-descriptions-item>
      </el-descriptions>
      <el-table
        v-loading="loading"
        :data="managerList"
      >
        <el-table-column
          label="用户姓名"
          align="center"
          key="nickName"
          prop="nickName"
        />
        <el-table-column
          label="活动标题"
          align="center"
          key="activityTitle"
          prop="activityTitle"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          v-if="managerList.activityType == 1"
          label="优惠券标题"
          align="center"
          key="couponTitle"
          prop="couponTitle"
          :show-overflow-tooltip="true"
        />
        <el-table-column
          label="活动类型"
          align="center"
          key="activityType"
          prop="activityType"
        >
        <template slot-scope="scope">
          <span v-if="scope.row.activityType == 0">优惠券</span>
          <span v-if="scope.row.activityType == 1">纯推广</span>
        </template>
        </el-table-column>
        <el-table-column
          label="优惠券使用状态"
          align="center"
          key="useStatus"
          prop="useStatus"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.useStatus == 0">未使用</span>
            <span v-if="scope.row.useStatus == 1">使用</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="pushTotal > 0"
        :total="pushTotal"
        :page.sync="pushForm.pageNum"
        :limit.sync="pushForm.pageSize"
        @pagination="getPushList"
      />
    </el-dialog>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商家头像" prop="parentId">
              <upload
                :value="form.pic"
                :limit="1"
                @uploadSuccess="uploadSuccess"
              ></upload>
            </el-form-item>
            <el-col :span="12">
              <el-form-item label="商户名称" prop="name">
                <el-input
                  v-model="form.name"
                  placeholder="请输入商户名称"
                  maxlength="10"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="负责人" prop="leader">
                <el-input
                  v-model="form.leader"
                  placeholder="请输入负责人"
                  maxlength="10"
                />
              </el-form-item>
            </el-col>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="商户手机号码" prop="phone">
              <el-input
                v-model="form.phone"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户邮箱" prop="email">
              <el-input
                v-model="form.email"
                placeholder="请输入商户邮箱"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="营业时间" prop="businessTime">
              <!-- <el-input v-model="form.businessTime" placeholder="请输入营业时间" maxlength="11"/> -->
                <el-time-picker
                  is-range
                  v-model="timeValue"
                  size="small"
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="--"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围">
                </el-time-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="热度" prop="heat">
              <el-input
                v-model="form.heat"
                placeholder="请输入热度"
                maxlength="50"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="商户状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                  >{{ dict.dictLabel }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--    修改/添加用户信息-->
    <el-dialog
      :title="userTitle"
      :visible.sync="userAdOpen"
      width="700px"
      append-to-body
    >
      <el-form
        ref="userQuery"
        :model="userQuery"
        :rules="rules"
        label-width="100px"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户头像" prop="parentId">
              <upload
                v-model="userQuery.avatar"
                :value="userQuery.avatar"
                :limit="1"
                @uploadSuccess="uploadUserSuccess"
              ></upload>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!userQuery.userId">
            <el-form-item label="用户账号" prop="userName" label-width="100px">
              <el-input
                v-model="userQuery.userName"
                placeholder="请输入用户账号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!userQuery.userId">
            <el-form-item label="用户密码" prop="password" label-width="100px">
              <el-input v-model="userQuery.password" placeholder="请输入用户姓名"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="nickName" label-width="100px">
              <el-input
                v-model="userQuery.nickName"
                placeholder="请输入用户姓名"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model.number="userQuery.phonenumber"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="userQuery.remark"
                type="textarea"
                placeholder="请输入备注"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" label-width="100px">
              <el-radio-group v-model="userQuery.status" >
                <el-radio label="0">正常</el-radio>
                <el-radio label="1">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUserForm">确 定</el-button>
        <el-button @click="userCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 商户详情列表弹窗 -->
    <el-dialog title="商户数据详情" :visible.sync="openList" append-to-body>
      <el-table ref="table" :data="detailList">
        <el-table-column label="商家ID" prop="id" />
        <el-table-column label="商户手机号码" prop="phone" />
        <el-table-column label="营业时间" prop="businessTime" />
        <el-table-column label="商户邮箱" prop="email" />
        <el-table-column label="热度" prop="heat" align="center" />
        <el-table-column
          label="创建时间"
          align="center"
          prop="createTime"
          width="160"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!--    充值-->
    <el-dialog
      title="充值"
      :visible.sync="rechargeOpen"
      width="30%"
      :before-close="rechargeClose"
    >
      <span style="display: block; margin-bottom: 20px">{{
        rechargeTitle
      }}</span>
      <el-form
        :model="rechargeQuery"
        ref="recharge"
        :rules="rules"
        class="demo-ruleForm"
      >
        <el-form-item prop="videoCount">
          <el-input
            v-model.number="rechargeQuery.videoCount"
            placeholder="请输入充值数量"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="rechargeClose">取 消</el-button>
        <el-button type="primary" @click="recharge">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listUser,
  getUser,
  addUser,
  updateUser,
  getTiktokShopInfo,
  shopAuth,
  addManagerUser,
  exportData,
  getUserList,
  getAuthQrCodeUrl,
  getUserInfo,
  updateShopUser,
  resetPwd,
  updateTiktokShopInfo,
  getAddress,
  deleteShopUser,
  getTreesList,
  pushList,
  getPushCount
} from "@/api/merchant/merchant";
import { transferVideoCount, addVideCount } from "@/api/acting/user";
import { getToken } from "@/utils/auth";
import { treeselect, listActing } from "@/api/acting/acting";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { downLoadExcel } from "@/utils/download";
import upload from "@/components/ImageUpload";
import QRCode from "qrcodejs2";
import { resetUserPwd } from "@/api/system/user";
import { mapState } from "vuex";
import { getProxyVideoCount } from "@/api/acting/acting";

export default {
  name: "merchant",
  components: { Treeselect, upload },
  data() {
    const numberRule = (rule, value, callback) => {
      if (Number(value) < this.rechargeMax) {
        if (Number.isInteger(Number(value)) && Number(value) > 0) {
          callback();
        } else {
          callback(new Error("请输入大于零的正整数"));
        }
      } else {
        callback(new Error("次数不能大于" + this.rechargeMax + "次"));
      }
    };
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      merchantName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 性别状态字典
      sexOptions: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      //详情信息表格
      detailList: [],
      //详情列表是否弹出层显示
      openList: false,
      //是否显示小程序开关
      miniSwitch: false,
      defaultProps: {
        children: "children",
        label: "label",
      },
      //用户列表弹窗
      userOpen: false,
      //推广列表弹窗
      pushOpen: false,
      //推广列表
      managerList: [],
      pushCountForm: [],
      //推广列表总条数
      pushTotal: 0,
      //充值弹窗
      rechargeOpen: false,

      //充值参数
      rechargeQuery: {
        type: 1, //0代理商 1商户
      },
      //最大充值数量
      rechargeMax: 99,
      //充值内容
      rechargeTitle: "",
      //判断给商家还是代理商充值
      usertype: 1,
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_URL + "/system/user/importData",
      },

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined,
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户名称`, visible: true },
        { key: 2, label: `用户昵称`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true },
      ],
      // 表单校验
      rules: {
        nickname: [
          { required: true, message: "用户名称不能为空" },
          { min: 2, message: "用户名称最少两个字符", trigger: "blur" },
        ],
        douyinUrl: [{ required: true, message: "商家抖音主页不能为空" }],
        address: [{required: true, message: '地理位置不能为空'}],
        name: [{ required: true, message: "商户名称不能为空" }],
        leader: [{ required: true, message: "负责人不能为空" }],
        phone: [{ required: true, message: "商户手机号码不能为空" },
                {
                  pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                  message: "请输入正确的手机号码",
                  trigger: "blur",
                },
              ],
        userName: [
          { required: true, message: "用户账号不能为空", trigger: 'blur'},
          {
            min: 2,
            max: 20,
            message: "用户名称长度必须介于 2 和 20 之间",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "用户密码不能为空", trigger: "blur" },
          {
            min: 5,
            max: 20,
            message: "用户密码长度必须介于 5 和 20 之间",
            trigger: "blur",
          },
        ],
        nickName: [
          {required: true, message: '用户姓名不能为空'},
          {min: 2, max: 10, message: '用户姓名长度介于2~8之间', trigger: 'blur'}
        ],
        videoCount: [
          { required: true, message: "充值次数不能为空" },
          { type: "number", message: "必须为数字值" },
          { validator: numberRule, trigger: ["change", "blur"] },
        ],
        email: [
          { required: true, message: "邮箱不能为空"},
          {
            type: "email",
            message: "'请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        phonenumber: [
          { required: true, message: '手机号码不能为空'},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
      },
      //商户下用户列表数据
      merchantUserList: [],
      //用户列表总数
      userTotal: 0,
      //用户列表表单
      userForm: {
        pageNum: 1,
        pageSize: 10,
      },
      //推广列表表单
      pushForm: {
        pageNum: 1,
        pageSize: 10,
      },
      //用户新增修改表单
      userQuery: {},
      //修改添加用户弹窗标题
      userTitle: "",
      //商户Id
      shopId: "",
      //用户添加修改弹窗
      userAdOpen: false,
      //打开二维码弹窗
      codeOpen: false,

      //用户抖音信息开关
      TikTokOpen: false,
      //用户抖音信息请求参数
      TikTokForm: {},
      //地址列表
      poiList: [],
      //营业时间默认值
      timeValue:['07:00','19:00']
    }
  },
  computed: {
    ...mapState({
      rolesKey: (state) => state.user.rolesKey,
    }),
  },
  watch: {
    // 根据名称筛选部门树
    merchantName(val) {
      this.$refs.merchantTree.filter(val);
    },
  },
  created() {
    this.getList();
    if (this.rolesKey == "00") {
      this.getTreeselect();
    }
    this.getDicts("sys_normal_disable").then((response) => {
      this.statusOptions = response.data;
      this.statusOptions.forEach((item) => {
        item.dictValue = Number(item.dictValue);
      });
    });
    this.getDicts("sys_user_sex").then((response) => {
      this.sexOptions = response.data;
      this.sexOptions.forEach((item) => {
        item.dictValue = Number(item.dictValue);
      });
    });
    this.getConfigKey("sys.user.initPassword").then((response) => {
      this.initPassword = response.msg;
    });
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    //选中地址函数
    changePoi(e) {
      // console.log(e);
      this.poiList.forEach((item) => {
        if (item.address == e) {
          let local = [];
          //将经纬度转为数组
          local = item.location.split(",");
          this.TikTokForm.address = item.province + item.city + item.district + item.address;
          this.TikTokForm.log = local[0];
          this.TikTokForm.lat = local[1];
          this.TikTokForm.poiName = item.poiName;
          this.TikTokForm.poiId = item.poiId;
        }
      });
    },
    //地址资源分组列表
    getPoiList(address) {
      getAddress({
        address: address,
      }).then((response) => {
        this.poiList = response.data;
      });
    },
    //远程搜索方法
    remoteMethod(query) {
      getAddress({
        address: query,
      }).then((res) => {
        this.poiList = res.data;
      });
    },
    /** 查询代理商下拉树结构 */
    getTreeselect() {
      getTreesList().then((response) => {
        this.deptOptions = response.data;
        console.log(this.deptOptions)
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.proxyId = data.id;
      this.getList();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.userName + '"用户吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeUserStatus(row.userId, row.status);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    //

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    //关闭商家抖音信息弹窗
    TikTokCancel() {
      this.TikTokOpen = false;
      this.TikTokForm = {};
      this.resetForm("TikTokForm");
    },
    // 用户取消按钮
    userCancel() {
      this.userAdOpen = false;
      this.userReset();
    },
    // 表单重置
    reset() {
      this.form = {
        businessTime:['07:00','19:00']
      }
      this.resetForm('form')
    },
    userReset() {
      this.userQuery = {};
      this.resetForm("userQuery");
    },
    //上传用户头像
    uploadSuccess(url) {
      this.form.pic = url;
    },
    //新增用户上传头像
    uploadUserSuccess(url) {
      this.userQuery.avatar = url;
    },
    //抖音账号授权
    TiktokEmpower(row) {
      getAuthQrCodeUrl({
        shopId: row.id,
      }).then((res) => {
        this.$refs.qrCodeDiv.innerHTML = "";

        this.$nextTick(function () {
          this.bindQRCode(res.msg);
        });
      });

      this.codeOpen = true;
    },
    //获取商家抖音信息
    getTikTokInfo(row) {
      getTiktokShopInfo(row.id).then((res) => {
        if (res.code == 200) {
          this.TikTokOpen = true;
          this.TikTokForm = res.data;
          if (
            res.data.miniAppId !== undefined ||
            res.data.miniAppTitle !== undefined ||
            res.data.miniAppUrl
          ) {
            // this.miniSwitch = true;
          }
        }
      });
    },
    //修改抖音用户信息
    updateTiktokInfo() {
      updateTiktokShopInfo(this.TikTokForm).then((res) => {
        if (res.code == 200) {
          this.msgSuccess("修改成功");
        }
      });
    },
    //二维码函数
    bindQRCode: function (url) {
      new QRCode(this.$refs.qrCodeDiv, {
        text: url,
        width: 200,
        height: 200,
        colorDark: "#333333", //二维码颜色
        colorLight: "#ffffff", //二维码背景色
        correctLevel: QRCode.CorrectLevel.L, //容错率，L/M/H
      });
    },
    //充值
    recharge() {
      this.$refs["recharge"].validate((valid) => {
        if (valid) {
          if (this.usertype == 1) {
            addVideCount(this.rechargeQuery).then((res) => {
              this.msgSuccess("充值成功");
              this.getList();
              this.rechargeClose();
            });
          } else {
            transferVideoCount({
              shopId: this.shopId,
              videoCount: this.rechargeQuery.videoCount,
            }).then((res) => {
              this.msgSuccess("充值成功");
              this.getList();
              this.rechargeClose();
            });
          }
        }
      });
    },

    //充值操作  usertype 1为管理员 2为代理商
    handleRecharge(row, usertype) {
      this.rechargeOpen = true;
      this.rechargeQuery.publicId = row.id;
      this.usertype = usertype;
      if (usertype == 2) {
        this.shopId = row.id;
      }
      getProxyVideoCount().then((res) => {
        this.rechargeMax = res.data;
        this.rechargeTitle =
          '请输入给商户"' +
          row.name +
          '"充值的视频数量。最大充值数量为' +
          res.data +
          "次";
      });
    },
    //充值取消操作
    rechargeClose() {
      this.rechargeOpen = false;
      this.rechargeTitle = "";

      this.rechargeQuery = {
        type: 1,
      };
      this.resetForm("recharge");
    },
    //查看用户列表信息操作
    handleUserList(row) {
      this.userForm.shopId = row.id;
      this.userOpen = true;
      this.userForm.shopId = row.id;
      this.usersList();
    },
    //查看用户列表信息
    async usersList() {
     await getUserList(this.userForm).then((res) => {
        this.merchantUserList = res.rows;
        this.userTotal = res.total;
      });
    },
    /**查看商户列表详情 */
    getDetail(row) {
      this.detailList = []
      const getid = row.id || this.ids
      getUser(getid).then((response) => {
        console.log(typeof response.data);
        this.detailList.push(response.data);
        this.openList = true;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      delete this.queryParams.proxyId
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "handleResetPwd":
          this.handleResetPwd(row);
          break;
        case "handleAuthRole":
          this.handleAuthRole(row);
          break;
        default:
          break;
      }
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();

      // getUser().then(response => {
      //   this.postOptions = response.data.posts;
      //   this.roleOptions = response.data.roles;
      //   this.form.password = this.initPassword;
      //
      // });
      // if (row != undefined) {
      //
      // }else {
      //
      // }
      this.form.status = 0
      this.title = "新增商户";
      this.open = true;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.id || this.ids;
      getUser(userId).then((response) => {
        this.form = response.data;

        if(this.form.businessTime == null){
          this.timeValue = ['07:00','19:00']
        }else {
           this.timeValue =  this.form.businessTime.split('-');
        }
        this.open = true
        this.title = '修改商户'
      })
    },
    /** 新增用户按钮操作 */
    handleUserAdd(row) {
      this.userReset();
      this.userTitle = "新增用户";
      this.userAdOpen = true;
      this.userQuery.shopId = this.userForm.shopId;
      this.userQuery.status = "0"
    },
    /** 修改用户按钮操作 */
    handleUserUpdate(row) {
      this.userReset();
      // console.log(row);
      const userId = Number(row.userId);
      getUserInfo({
        userId: userId,
      }).then((response) => {
        this.userQuery = response.data.user;
        this.userTitle = "修改用户";
        this.userAdOpen = true;
      });
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      const _this = this;
      this.$confirm(
        '是否重置"' + row.userName + '"用户的密码?默认密码为123456',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(function () {
        resetPwd({
          userId: row.userId,
          password: "123456",
        }).then(() => {
          _this.msgSuccess("重置成功");
        });
      }).catch(() => {
        _this.$message({
            type: 'info',
            message: '已取消重置密码'
          });
      });
    },
    delShopUser(row){
      this.$confirm(
        '是否确认删除用户"' + row.nickName + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return deleteShopUser(row.userId);
        })
        .then(() => {
          this.usersList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});

    },
    /**推广列表按钮 */
    managerPush(row) {
      this.pushForm.userId = row.userId;
      this.getPushList()
      getPushCount({
        userId: row.userId
      }).then((res)=>{
        this.pushCountForm = res.data
        this.pushOpen = true
      })
    },
    //获取推广列表
    getPushList(){
      pushList(this.pushForm).then((res) => {
        this.managerList = res.rows;
        this.pushOpen = true;
        this.pushTotal = res.total;
      });
    },
    /** 分配角色操作 */
    handleAuthRole: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.businessTime = this.timeValue[0] + "-" + this.timeValue[1];
          if (this.form.id != undefined) {
            updateUser(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUser(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList()
            });

          }
        }
      });
    },
    submitUserForm: function () {
      this.$refs["userQuery"].validate((valid) => {
        if (valid) {
          if (this.userQuery.userId != undefined) {
            updateShopUser(this.userQuery).then((response) => {
              this.msgSuccess("修改成功");
              this.userAdOpen = false;
              this.usersList();
            });
          } else {
            addManagerUser(this.userQuery).then((response) => {
              this.msgSuccess("新增成功");
              this.userAdOpen = false;
              this.usersList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$confirm(
        '是否确认删除用户编号为"' + userIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delUser(userIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      downLoadExcel("/system/shop/manager/export", this.queryParams);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },

    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
  },
};
</script>
